'use strict';

const axios = require('axios');
const urlJoin = require('url-join');
const semver = require('semver');

async function getNpmInfo(npmName,registry) {
    if(!npmName){
        return null
    }
    const registryUrl = registry || getDetfaultRegistry()
    const npmInfoUrl = urlJoin(registryUrl,npmName)
    return axios.get(npmInfoUrl).then(res=>{
        if(res.status === 200){
            return res.data
        }
        return null
    }).catch(err=> Promise.reject(err)
    )
}

function getDetfaultRegistry(isOriginal=false){
    return isOriginal ? 'https://registry.npmjs.org' : 'https://registry.npm.taobao.org'
}

async function getNpmVersions(npmName){
    const data = await getNpmInfo(npmName)
    const versions = Object.keys(data.versions);
    return versions || []
}

function getSemverVersions(baseVersion,versions){
    const gtBaseVersions = versions.filter(version=>
            semver.satisfies(version,`^${baseVersion}`)
        ).sort((a,b)=>semver.gt(b,a))
    return gtBaseVersions

}

async function getNpmSemverVersion(currentVersion,npmName){
    const versions = await getNpmVersions(npmName);
    const newVersions = getSemverVersions(currentVersion,versions)
    if(newVersions && newVersions.length>0){
        return newVersions[0]
    }
}

module.exports = {
    getNpmInfo,
    getNpmVersions,
    getNpmSemverVersion
};
